package com.zhouchb.test.设计模式.代理模式.动态代理;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Create 2023-08-07 21:20
 * @Description
 */
interface Human{
    public  String believe();
    public void eat();
}
class SuperMan implements Human{

    @Override
    public String believe() {
        return "I believe i can fly";
    }

    @Override
    public void eat() {
        System.out.println("我喜欢四川麻辣烫");
    }
}
class ProxyFactory{
    public static Object getProxyInstance(Object obj){
        MyInvocationHandler myInvocationHandler = new MyInvocationHandler();
        myInvocationHandler.bind(obj);
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),myInvocationHandler);
    }
}
class MyInvocationHandler implements InvocationHandler{
        private Object object;
        public void bind(Object obj){
            this.object = obj;
        }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return method.invoke(object,args);
    }
}
public class DynamicProxy {
    public static void main(String[] args) {
        SuperMan superMan = new SuperMan();
        Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan);
        String believe = proxyInstance.believe();
        System.out.println(believe);
        proxyInstance.eat();
    }
}

